import React, { useEffect, useState } from 'react'
import http from '../../api/http'
import { List, Image } from 'antd';
import { InfiniteScroll } from 'antd-mobile'
import type { FormProps } from 'antd';
import { Button, Form, Input } from 'antd';
import { useNavigate } from 'react-router-dom';

type FieldType = {
  title?: string;
  tag?: string;
};

function Index() {

  const navigate = useNavigate()

  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [hasMore, setHasMore] = useState(true)
  const [title, setTitle] = useState('')
  const [tag, setTag] = useState('')

  const fetchList = async () => {
    const params: {
      page: number,
      pageSize: number,
      keyword?: string,
      tag?: string
    } = {
      page,
      pageSize
    }
    if (title) params.keyword = title;
    if (tag) params.tag = tag;
    const res = await http.get('/article/list', {
      params
    })
    console.log(res, '列表')
    const { count, rows } = res.data;
    setList([...list, ...rows])
    setTotal(page + 1)
  }

  useEffect(() => {
    fetchList()
  }, [title, tag])

  // 搜索
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    setTitle(values.title)
    setTag(values.tag)
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 去详情
  const handleToDetail = (id) =>{
    navigate(`/detail/${id}`)
  }

  return (
    <div>
      {/* 搜索 */}
      <Form
        name="basic"
        layout='inline'
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 1600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="标题"
          name="title"
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="标签"
          name="tag"
        >
          <Input />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            重置
          </Button>
        </Form.Item>

      </Form>
      {/* 渲染 */}
      <List
        dataSource={list}
        renderItem={(item) => (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <h1 onClick={()=>handleToDetail(item.id)}>{item.title}</h1>
                <p>内容：{item.content}</p>
                <p>
                  <span>创建时间: {item.createdAt}</span>&ensp;
                  <span>浏览量: {item.viewCount}</span>
                </p>
              </div>
              <Image
                width={150}
                height={150}
                src="https://fastly.picsum.photos/id/425/200/300.jpg?hmac=P1vjZ6T-wo-aULK7NbbLYxIaV92_0q56o0BFWcWOdmo"
              />
            </div>
            <hr />
          </div>
        )}
      />
      <InfiniteScroll loadMore={fetchList} hasMore={hasMore} />
    </div>
  )
}

export default Index
